package com.scriptlib;

import android.media.Image;
import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AJFunc {
    public Object ScreenCapturer;
    public Method CaptureMethod;
    private Object Files;
    private Method GetPathMethod;

    public static AJFunc Instance = null;

    public static AJFunc GetInstance(Object obj) {
        if (Instance == null) {
            Instance = new AJFunc(obj);
        }
        return Instance;
    }

    /**
     * 版本号_以发布日期命名
     */
    static public String Version() {
        return "21.02.03";
    }

    static public String GetInfo() {
        return "https://gitee.com/yiszza/ScriptLib";
    }

    public Image Capture() {
        try {
            return (Image) CaptureMethod.invoke(ScreenCapturer);
        } catch (InvocationTargetException | IllegalAccessException e) {
            Log.e("ScriptLib", e.toString());
            return null;
        }
    }

    public String GetPath(String path) {
        try {
            return (String) GetPathMethod.invoke(Files, path);
        } catch (InvocationTargetException | IllegalAccessException e) {
            Log.e("ScriptLib", e.toString());
            return "";
        }
    }

    public AJFunc(Object obj) {
        try {
            Field images = obj.getClass().getDeclaredField("images");
            images.setAccessible(true);
            Object _images = images.get(obj);
            assert _images != null;
            Field mScreenCapturer = _images.getClass().getDeclaredField("mScreenCapturer");
            mScreenCapturer.setAccessible(true);

            ScreenCapturer = mScreenCapturer.get(_images);
            CaptureMethod = mScreenCapturer.getType().getDeclaredMethod("capture");
            CaptureMethod.setAccessible(true);

            Field files = obj.getClass().getDeclaredField("files");
            Files = files.get(obj);
            GetPathMethod = files.getType().getDeclaredMethod("path", String.class);
            GetPathMethod.setAccessible(true);
        } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException e) {
            Log.e("ScriptLib", e.toString());
        }
    }
}
